using System;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.Utilities;
using System.Diagnostics;

namespace XSLTListitemWebPart
{
    public class AssetUrlSelectorEditorPart : EditorPart
    {
        private AssetUrlSelectorEditorPartControl selectorcontrol;

        #region Public Properties
        public string AssetUrlProperty { get; set; }

        public bool? AllowExternalUrls { get; set; }

        public bool? UseImageAssetPicker { get; set; }

        public bool? AssetPickerButtonVisible { get; set; }

        public string PickerButtonText { get; set; }

        public string LabelText { get; set; }

        public string ToolTipText { get; set; }
        #endregion

        protected string AssetUrl
        {
            get
            {
                System.Reflection.PropertyInfo propertyinfo = WebPartToEdit.GetType().GetProperty(AssetUrlProperty);
                if (propertyinfo == null) throw new ArgumentOutOfRangeException("AssetUrlProperty");

                object value = propertyinfo.GetValue(WebPartToEdit, null);
                return value != null ? value.ToString() : null;
            }
            set
            {
                System.Reflection.PropertyInfo propertyinfo = WebPartToEdit.GetType().GetProperty(AssetUrlProperty);
                if (propertyinfo == null) throw new ArgumentOutOfRangeException("AssetUrlProperty");

                propertyinfo.SetValue(WebPartToEdit, value, null);
            }
        }

        protected override void CreateChildControls()
        {
            selectorcontrol = (AssetUrlSelectorEditorPartControl)Page.LoadControl("/_Layouts/XSLTListitemWebPart/AssetUrlSelectorEditorPartControl.ascx");
            selectorcontrol.Label.Text = LabelText;
            selectorcontrol.ID = "ausepc";
            selectorcontrol.AssetUrlSelector.AssetUrlChanged += new EventHandler(selector_AssetUrlChanged);
            if (AllowExternalUrls.HasValue) selectorcontrol.AssetUrlSelector.AllowExternalUrls = AllowExternalUrls.Value;
            if (UseImageAssetPicker.HasValue) selectorcontrol.AssetUrlSelector.UseImageAssetPicker = UseImageAssetPicker.Value;
            if (AssetPickerButtonVisible.HasValue) selectorcontrol.AssetUrlSelector.AssetPickerButtonVisible = AssetPickerButtonVisible.Value;
            if (PickerButtonText != null) selectorcontrol.AssetUrlSelector.PickerButtonText = PickerButtonText;
            this.Controls.Add(selectorcontrol);
        }

        void selector_AssetUrlChanged(object sender, EventArgs e)
        {
            if (selectorcontrol.AssetUrlSelector != null)
            {
                string selAss = selectorcontrol.AssetUrlSelector.AssetUrl;

                string df = "/DispForm.aspx?ID=";
                if (selAss != null && selAss.Contains(df))
                {
                    int idx = selAss.IndexOf(df);
                    string webandlist = selAss.Substring(0, idx);
                    int listitemid = int.Parse(selAss.Substring(df.Length + idx));

                    try
                    {

                        using (SPWeb web = SPContext.Current.Site.OpenWeb(webandlist))
                        {
                            SPList list = web.GetList(webandlist);
                            SPListItem listitem = list.GetItemById(listitemid);

                            selAss = SPUrlUtility.CombineUrl(web.ServerRelativeUrl, listitem.Url);
                        }
                    }
                    catch (Exception ex)
                    {
                        SPSecurity.RunWithElevatedPrivileges(delegate
                        {
                            EventLog.WriteEntry(this.GetType().FullName, ex.ToString());
                        });
                    }

                    /*SPList list = SPContext.Current.Site.RootWeb.GetList(webandlist);
                    SPListItem listitem = list.GetItemById(listitemid);
                    selAss = SPContext.Current.Site.RootWeb.ServerRelativeUrl + listitem.Url;*/
                }
                selectorcontrol.AssetUrlSelector.AssetUrl = selAss;

                AssetUrl = selAss;
            }
        }

        public override void SyncChanges()
        {
            EnsureChildControls();
            if (selectorcontrol.AssetUrlSelector != null)
            {
                selectorcontrol.AssetUrlSelector.AssetUrl = null;

                if (!string.IsNullOrEmpty(AssetUrl))
                {
                    selectorcontrol.AssetUrlSelector.AssetUrl = AssetUrl;
                }
            }
        }

        public override bool ApplyChanges()
        {
            if (selectorcontrol.AssetUrlSelector != null)
            {
                AssetUrl = selectorcontrol.AssetUrlSelector.AssetUrl;
            }
            else return false;
            return true;
        }

        public AssetUrlSelectorEditorPart(string AssetUrlProperty, string title)
        {
            this.AssetUrlProperty = AssetUrlProperty;
            this.Title = title;
        }

    }
}
